from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from .serializers import UserModelSerializer
from .models import User
from rest_framework.views import APIView
from .utils import get_user_by_accout
from rest_framework import status

# 短信验证码的
import random
import logging
from django_redis import get_redis_connection
from luffyapi.libs.smsronglian_sdk.SendMessage import send_message
from django.contrib.auth.hashers import make_password

from mycelery.email.tasks import send_sms


# Create your views here.


class UserAPIView(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserModelSerializer


class MobileAPIView(APIView):
    def get(self, request, mobile):
        user = get_user_by_accout(mobile)
        if user is not None:
            return Response({'msg': '抱歉，该手机号已被注册'}, status=status.HTTP_400_BAD_REQUEST)
        return Response({'msg': '手机号没问题'}, status=status.HTTP_200_OK)


logger = logging.getLogger('django')


class SMSAPIView(APIView):
    """实现验证码接口"""

    def get(self, request, mobile):
        redis_conn = get_redis_connection('sms_code')
        check_ret = redis_conn.get(f'mobile_{mobile}')

        if check_ret:
            return Response({'msg': '60秒内不允许再次点击发送验证码'}, status=status.HTTP_403_FORBIDDEN)
        try:
            sms_code = '%06d' % random.randint(0, 99999)

            # 将随机 验证码保存到redis中
            # 创建管道
            pipe = redis_conn.pipeline()
            # 开启管道
            pipe.multi()
            pipe.setex(f'sms_{mobile}', 60 * 5, sms_code)
            # 设置一个时间间隔的键值对
            pipe.setex(f'mobile_{mobile}', 60, '_')
            # 统一一次执行
            pipe.execute()

            send_sms.delay(mobile, sms_code)
            return Response({'msg': '手机验证码已发送'})
        except:
            logger.error('服务器内部错误')
            return Response({'msg': '服务器内部错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class IDAPIView(APIView):
    def post(self, request):
        id = request.POST.get('id')
        password = make_password(request.POST.get('password'))
        User.objects.filter(id=id).update(password=password)
        return Response({"ret": '成功'}, status=status.HTTP_200_OK)
        # User.objects.filter(id=id).update(password=)
